package com.ticket.util;

import java.io.*;

public class FileUtil {

    private String path = "/Users/lihua/workspace/java/ynjtc-work/train-ticket/";

    /**
     * 从指定文件中或者数据
     * @param fileName
     * @return
     */
    public String getContent(String fileName){
        String filePath = path + fileName;
        BufferedInputStream bis = null;
        try {
            File file = new File(filePath);
            if(!file.exists()){
                return null;
            }
            byte [] content = new byte[1024];
            bis = new BufferedInputStream( new FileInputStream(filePath));
            bis.read(content);
            return new String(content).trim();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }finally {
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 向文件中写入数据
     * @param fileName
     * @param content
     * @return
     */
    public boolean saveContent(String fileName,String content){
        String filePath = path + fileName;
        BufferedOutputStream bos = null;
        try {
            File file = new File(filePath);
            if(!file.exists()){
                file.createNewFile();
            }
            bos = new BufferedOutputStream(new FileOutputStream(filePath));
            bos.write(content.trim().getBytes());
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }finally {
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
